/*
 * @Author: ziqi jhzq12345678
 * @Date: 2024-08-23 14:22:34
 * @LastEditors: wangdazhuang
 * @LastEditTime: 2025-02-21 09:16:11
 * @FilePath: /pornhub_app/lib/http/api/login.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/advertisements/ad_resp_model.dart';
import 'package:pornhub_app/model/line/lineModel.dart';
import 'package:pornhub_app/model/user/user_info_model.dart';
import 'package:pornhub_app/services/storage_service.dart';
import 'package:pornhub_app/services/user_service.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart' hide Response;
import 'package:pornhub_app/utils/conditional_future.dart';
import 'package:pornhub_app/utils/logger.dart';

final us = Get.find<UserService>();
final storageService = Get.find<StorageService>();
//登录
Future login(String deviceId) async {
  String? params;
  if (kIsWeb) {
    var ppp = Uri.base.queryParameters;
    params = jsonEncode(ppp).toString();
  } else {
    final text = await Clipboard.getData(Clipboard.kTextPlain);
    final content = text?.text;
    if (content != null && content.isNotEmpty) {
      logger.d('text from paste board >>> $content');
    }
    params = content;
  }

  try {
    final resp = storageService.token != null
        ? us.user
        : await httpInstance.post<UserInfo>(
            url: "user/traveler",
            body: {
              "deviceId": deviceId,
              'code': params,
              'chCode': const String.fromEnvironment('CHANNEL')
            },
            complete: UserInfo.fromJson);
    if (resp == null || resp is UserInfo == false) return;
    UserInfo u = resp;
    if (u.imgDomain != null && u.imgDomain!.isNotEmpty) {
      storageService.setDomain(u.imgDomain!);
    }
    storageService.setToken(storageService.token ?? u.token!);
    storageService.saveUserInfo(u);
    await us.updateAll();
    await webSelectline(u);
    await useFetchAdData();
    us.getOnlineService();
  } catch (_) {}
}

//拉取广告
Future useFetchAdData() async {
  final ads = await httpInstance.get<AdRspModel>(
      url: 'sys/advertisement/list', complete: AdRspModel.fromJson);
  if (ads is AdRspModel) {
    final t = DateTime.now().millisecondsSinceEpoch;
    final advertisementInfos = ads.advertisementInfos ?? [];
    // 过滤掉过期广告
    List<AdvertisementInfos> unOverdueAds = advertisementInfos
        .where((v) => DateTime.parse(v.adStopTime!).millisecondsSinceEpoch > t)
        .toList();
    ads.advertisementInfos = unOverdueAds;
    storageService.setAdvertisement(ads);
  }
}

// 图片视频cdn上报
void useFetchLineReport(params) async {
  await httpInstance.post(url: 'sys/reportCdnSelect', body: params);
}

Future<int?> _webSelectFastestLine(List<String> domains) async {
  final option = BaseOptions(connectTimeout: const Duration(seconds: 10));
  final futures = domains.map((e) async {
    try {
      return await Dio(option).get(e);
    } catch (e) {
      return Future.value(null);
    }
  }).toList();
  final fatest = await ConditionalFuture<Response?>(
    futures,
    (res) =>
        res != null &&
        res.statusCode != null &&
        res.statusCode! >= 200 &&
        res.statusCode! < 300,
  ).anyIndexed();

  if (fatest == null) return null;
  return fatest.item1;
}

//图片视频选线
Future webSelectline(UserInfo user) async {
  try {
    final webline = await httpInstance.get<LineModel>(
      url: 'sys/getImgAndVideoCdnList',
      complete: LineModel.fromJson,
    );
    if (webline is LineModel) {
      final imgCdn = webline.imgCdnList ?? [];
      final videoCdn = webline.videoCdnList ?? [];
      final List<String> domains = imgCdn.map((v) => v.url.toString()).toList();
      final result = await Future.wait([
        _webSelectFastestLine(imgCdn.map((e) => e.domain ?? '').toList()),
        _webSelectFastestLine(videoCdn.map((e) => e.domain ?? '').toList()),
      ]);
      final imgFastest = result[0] != null ? imgCdn[result[0]!] : null;
      final videFastest = result[1] != null ? videoCdn[result[1]!] : null;

      if (imgFastest != null) {
        if (imgFastest.url!.isNotEmpty) {
          domains.remove(imgFastest.url);
          storageService.setDomians(domains);
        }
        user.imgDomain = imgFastest.url;
        // 更新用户信息-图片域名
        storageService.saveUserInfo(user);
      }
      final params = {
        'imgCdnId': imgFastest?.id ?? '',
        'videoCdnId': videFastest?.id ?? ''
      };
      if (params['imgCdnId'] != '' || params['videoCdnId'] != '') {
        useFetchLineReport(params);
      }
    }
  } catch (e) {
    logger.d('webSelectLine exception $e');
  }
}
